<template>
  <div class="header">
        <div class="header-left fl">
           <i class="iconfont icon-shizhongclock74" style="font-size: 28px;"></i>
           <!-- 时间 -->
           <span class="time">{{ time }}</span>
           <!-- 日期 -->
           <span class="date">{{ date }}</span>
           <!-- 周末 -->
           <span class="week">{{ week }}</span>
        </div>
        <div class="header-center fl">
            <div class="header-title" >
              <div class="logo-title-container">
                <img src="../../assets/logo.png" alt="公司Logo" class="company-logo">
                <span class="title-text">{{ $t("message.title") }}</span>
              </div>
            </div>
            <div class="header-img"></div>
        </div>
        <div class="header-right fl">
          <div class="errorList" style="margin-right: 14px;" @click="openErrorList">
            <!-- 超级管理员 -->
            <span class="el-dropdown-link superAdmin" >   
              <template v-if="indexDbNum > 0">
                <el-badge class="item" :value="indexDbNum">
                  <el-icon size="20px" style="margin-right:3px;" color="#2980b9"><el-icon><BellFilled /></el-icon></el-icon>
                </el-badge>
                <span style="font-size: 14px;">{{ $t("message.info") }}</span>
              </template> 
              <template v-else>
                <el-icon size="20px" style="margin-right:5px;" color="#2980b9"><el-icon><BellFilled /></el-icon></el-icon>
                <span style="font-size: 14px;" v-if="isLabel">{{ $t("message.info") }}</span>
              </template>
          </span>
        </div>
          <!-- 阈值设置 -->
          <el-dropdown trigger="click" style="margin-right: 12px;">
            <!-- 超级管理员 -->
            <span class="el-dropdown-link superAdmin">    
              <el-icon size="20px" style="margin-right:3px;" color="#2980b9"><el-icon><Grid /></el-icon></el-icon>
              <span style="font-size: 14px" v-if="isLabel">
                  {{ $t("message.threshold") }}
              </span>
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-for="item in orderList" :key="item.id" @click="openPup(item.id)">{{ $t(item.orderName) }}</el-dropdown-item>
            </el-dropdown-menu>
          </template>
    </el-dropdown>
          <el-dropdown trigger="click">
            <!-- 超级管理员 -->
            <span class="el-dropdown-link superAdmin">    
              <el-icon size="20px" style="margin-right:3px;" color="#2980b9"><UserFilled /></el-icon>
                <span style="font-size: 12px;" v-if="isLabel">
                  {{ $t("message.admin") }}
                </span>
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item><router-link to="/admin" style="text-decoration: none; color: #333;">{{ $t("message.bgMan") }}</router-link></el-dropdown-item>
              <el-dropdown-item @click="openSetting">{{ $t("message.user_setting") }}</el-dropdown-item>
              <el-dropdown-item @click="exitLogin">{{ $t("message.logout") }}</el-dropdown-item>
            </el-dropdown-menu>
          </template>
    </el-dropdown>
    
    <!-- 报警列表 -->
    <div class="catchNormal">
      <img src="../../assets/images/normal.png" v-if="alarm_type == 0"/>
      <img src="../../assets/images/warning.png" v-else-if="alarm_type == 1" @click="changeWarningStatus"/>
      <img src="../../assets/images/diable.png" v-else  @click="changeWarningStatus"/>
    </div>
    <div class="fullscreen">
      <i @click="taggleFullscreen" v-if="!isFullscreen" class="iconfont icon-quanping" style="color:#3481b7;font-size:19px;" title="全屏"></i>
      <i @click="taggleFullscreen" v-else class="iconfont icon-tuichuzhuanhuan" style="color:#3481b7;font-size:19px;" title="退出全屏"></i>
    </div>
      </div>
      <div class="header-bottom fl"></div>
    </div>
  <el-dialog
      v-model="settingVisible"
      :title="$t('message.user_setting')"
      width="24%"
      draggable="true"
  >
    <el-form label-width="3rem;" :model="userSetting">
      <el-form-item :label="$t('message.data_refresh_rate')">
        <el-input-number v-model="userSetting.speed" :min="20" class="speedCss"></el-input-number>
      </el-form-item>
      <el-form-item :label="$t('message.voice_broadcast')">
        <el-switch
          v-model="isOpenVoice"
          class="mb-2"
          :active-text="$t('message.open')"
          :inactive-text="$t('message.close')"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="settingVisible = false">{{ $t("message.cancel") }}</el-button>
        <el-button type="primary" @click="changeSetting">
           {{ $t("message.confirm") }}
        </el-button>
      </span>
    </template>
  </el-dialog>
    <!-- 给传感器设置阈值 -->
    <el-dialog
      v-model="visible1"
      :title="proxy.$t('message.point') + device_currentId + proxy.$t(currentName) +proxy.$t('message.threshold')"
      width="25%"
      draggable="true"
  >
    <div class="slider-demo-block">
      <span class="demonstration">{{$t("message.alarm")}}：</span>
      <el-slider v-model="currentValue" :min="currentMin" :max="currentMax" show-input/>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible1 = false">{{ $t("message.cancel") }}</el-button>
        <el-button type="primary" @click="changeValue">
          {{ $t("message.confirm") }}
        </el-button>
      </span>
    </template>
  </el-dialog>
  
  <Teleport to="body">
    <catchList></catchList>
  </Teleport>
</template>

<script lang="ts" setup>
import { watch,ref } from 'vue'
import catchList from '../main/list.vue'

const isLabel = ref(false)

window.addEventListener('resize',() => {
  if (document.body.clientWidth  > 1280) {
    isLabel.value = true
  } else {
    isLabel.value = false
  }
})

function launchFullscreen(element) {
 if(element.requestFullscreen) {
  element.requestFullscreen();
 } else if(element.mozRequestFullScreen) {
  element.mozRequestFullScreen();
 } else if(element.webkitRequestFullscreen) {
  element.webkitRequestFullscreen();
 } else if(element.msRequestFullscreen) {
  element.msRequestFullscreen();
 }
}

function exitFullscreen() {
 if(document.exitFullscreen) {
  document.exitFullscreen();
 } else if(document.mozCancelFullScreen) {
  document.mozCancelFullScreen();
 } else if(document.webkitExitFullscreen) {
  document.webkitExitFullscreen();
 }
}
    import {ref,onMounted, reactive} from 'vue'
    import {storeToRefs} from 'pinia'
    import {userStore} from '../../store/user'
    import {useRouter} from 'vue-router';
    import {moduleStore} from '../../store/module'
    import { getCurrentInstance } from 'vue';
    let module_store = moduleStore()
    let {device_currentId,isFullscreen,alarm_type,isShowTip,isOpenVoice} = storeToRefs(module_store)
    import { IhttpReturn } from '../../until/interface';
    let {proxy} = getCurrentInstance()
    let store = userStore() // 本地数据存储
    let router = useRouter() // 本地的路由
    let { localWebsocket, indexDbNum, errList } = storeToRefs(store)
    const weekList = ["message.Monday","message.Tuesday","message.Wednesday","message.Thursday","message.Friday","message.Saturday","message.Sunday"]
    let time = ref('') // 时间
    let date = ref('') // 日期
    let week = ref('') // 周末 

    let visible1 = ref<boolean>() // 阈值设置对话框
    let currentName = ref<string>("") // 获取设备的名称
    let currentMax = ref<number>() // 获取设备的最大值
    let currentMin = ref<number>() // 获取设备的最小值
    let currentValue = ref<number>() // 获取设备的报警值
    let setting = reactive([])
      // 阈值设置 
      type obj = {
        orderName: string,
        id: number,
        refName: string
      }
  const orderList:Array<obj> = [
    {
      orderName: "message.uv",
      id: 1,
      refName: "uvcRef"
    },
    {
      orderName: "message.inf",
      id: 2,
      refName: "infRef"
    },
    {
      orderName: "message.tem",
      id: 3,
      refName: "temRef"
    },  {
      orderName: "message.hum",
      id: 4,
      refName: "humRef"
    },
    {
      orderName: "message.pre",
      id: 5,
      refName: "preRef"
    }
  ]
  let timer = reactive(null)
  let type_id = ref(0)
    // 打开设置阈值对话框
 const openPup = (id:number) => {
         // 检查setting数组是否已初始化
         if (!setting || setting.length === 0) {
           proxy.$message({showClose: true, message: "系统正在初始化，请稍后再试", type: "warning"})
           return
         }
         
         type_id.value = id - 1
        let index = device_currentId.value - 1
        
        // 检查索引是否有效
        if (!setting[index] || !setting[index][id - 1]) {
          proxy.$message({showClose: true, message: "设备配置未找到，请检查设备连接", type: "warning"})
          return
        }
        
				currentName.value = setting[index][id - 1].name // 获取设备的名称
				currentMax.value = setting[index][id - 1].normal_high // 获取设备的最大值
				currentMin.value = setting[index][id - 1].normal_low  // 获取设备的最小值
				currentValue.value = setting[index][id - 1].current_val // 获取设备的报警值
        visible1.value = true
 }
    // 修改阈值
    const changeValue = async () => {
      // let {data:res}:{data:IhttpReturn} = await proxy.$insideHttp.post("/socket/changeSerialport",{id:type_id.value + 1,device_id:[device_currentId.value],currentValue: currentValue.value})
      // if (res.code !== 200) return proxy.$message({showClose: true,message: res.msg,type: "warning"})
      store.changeValue({id:type_id.value,currentValue: currentValue.value,module_id: device_currentId.value })
      if(localWebsocket.value) {
        localWebsocket.value.send(JSON.stringify({
           action: 'changeVal',
           module_id: device_currentId.value,
           type_id: type_id.value,
           errorVal: currentValue.value
        }))
          proxy.$message({showClose: true,message: "修改阈值成功",type: "success"})
         visible1.value = false
      }
   }
    const toAdmin = ():void => {
        router.push("/admin")
    }
    const emit = defineEmits(['resetData','closeTimer','startTimer',"taggleDevice","resetView"])
    let userSetting:{speed:number} = reactive({
      speed: store.speed
    })

    let currentId = ref(1) // 当前模块id编号
    // @ts-ignore
    import deleteDataWorker from '@/worker/delData?worker' // 开始删除数据，只存入一周的数据
    let deleteWorker = new deleteDataWorker() // 删除数据
    import indexDb from '../../local/indexDb'
    import { adminStore } from '../../store/admin';
    onMounted(async () => {
      // 初始化系统的当前时间
      // 使用watchEffect来响应式地监听store.setting的变化
      const initSetting = () => {
        if (store.setting && store.setting.length > 0) {
          setting = store.setting
        } else {
          // 如果store.setting还没有数据，延迟重试
          setTimeout(initSetting, 100)
        }
      }
      initSetting()
      timer = setInterval(async () => {
            let {data:res}:{data:IhttpReturn} = await proxy!.$insideHttp.get("/socket/addRunDate")
            if (res.code == 200) {
              // 需要重新请求数据
              deleteWorker.postMessage(true)
              console.log("添加日期，查看数据库是否超过七天")
            }
        },600*1000)

      setInterval(() => {
        let date1 = new Date()
        time.value = date1.toLocaleTimeString()
        date.value = date1.toLocaleDateString().replace(/\//g,"-")
        week.value = proxy.$t(weekList[(date1.getDay() - 1)])
      },1000)
    })
    // 修改报警的状态值
    const changeWarningStatus = () => {
      if (alarm_type.value == 1) {
        alarm_type.value = 2
        isShowTip.value = false
      } else if(alarm_type.value == 2) {
        alarm_type.value = 1
        isShowTip.value = true
      }
    }
    // 改变用户选择参数
    const changeSetting = async () => {
      store.changeSpeed(userSetting.speed)    
      await proxy.$insideHttp.post('/socket/changeSpeed',{speed: userSetting.speed})
      settingVisible.value = false   
    }
    let settingVisible = ref<boolean>(false) // 控制设置面板的显示或者隐藏
    // 打开用户的设置面板
    const openSetting = () => {
      settingVisible.value = true
    }
    // 退出登录
    const exitLogin = async () => {
      localWebsocket.value.close()
      await proxy.$outsideHttp.put("/user/updateLoginStatus",{status: 0,token: store.userInfo.token})
      store.exitUser()
      router.push("/login")
    }

    // 全屏显示页面
    const taggleFullscreen = () => {
      if (!isFullscreen.value) {
         launchFullscreen(document.documentElement)
         isFullscreen.value = true
      } else {
          exitFullscreen()
          isFullscreen.value = false
      }
      emit("resetView")
    }
    let admin_store = adminStore()
    let {isOpenDrawer} = storeToRefs(admin_store)
      // 打开报警列表
      const openErrorList = async () => {
        if (!indexDbNum.value) return proxy.$message.info("暂无报警信息")
        isOpenDrawer.value = true
        let result:any = await indexDb.getAllData("errorList")
        errList.value = result.slice(0,10)
    }
 

</script>

<style lang="less" scoped>
.fl {
    float: left;
}
.speedCss {
  width: 160px;
}

// 头部的一些样式
.header {
    width: 100%;
    height: 80px;
    background-image: linear-gradient(to bottom, #20427a, #10152b);
   .header-left {
    width: 27%;
    height: 60px;
    color: white;
    display: flex;
    align-items: center;
    padding-left: 10px;
    padding-top: 10px;
    span {
      margin-right: 10px;
    }
    .time {
      margin-left: 10px;
      font-size: 20px;
    }
     .el-icon {
       font-weight: bold;
     }
}
.header-center {
    width: 45%;
    height: 70px;
    /* border: 1px solid red; */
    position: relative;
    .header-title {
    text-align: center;
    color: #ffffff;
    font-size: 28px;
    text-shadow: 0 0 4px #00d8ff;
    line-height: 30px;
    padding: 5px 0px;
    
    .logo-title-container {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 12px;
        
        .company-logo {
            width: 45px;
            height: 45px;
            border-radius: 8px;
            // box-shadow: 0 2px 8px rgba(0, 216, 255, 0.3);
            transition: all 0.3s ease;
            
            &:hover {
                transform: scale(1.05);
                box-shadow: 0 4px 12px rgba(0, 216, 255, 0.5);
            }
        }
        
        .title-text {
            font-weight: 600;
            letter-spacing: 1px;
            background: linear-gradient(135deg, #00d8ff, #ffffff);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
    }
}
 .header-img {
    background: url(../../assets/images/head.gif) no-repeat center center;
    background-size: 100%;
    height: 100%;
    width: 100%;
    position: absolute;
    top: 23px;
}
}
.header-right {
    width: 27%;
    height: 65px;
    line-height: 80px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    color: #fff;
    padding-right: 5px;
    font-size: 15px;
    .errorList {
      height: 30px;
      .superAdmin {
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 15px;
        .el-badge {
          height: 30px;
          display: flex;
          align-items: center;
        }
      }
    }
    .setting {
      display: flex;
      align-items: center;
      margin-right: 20px;
      font-size: 14px;
      img {
        width: 25px;
        height: 20px;
        margin-right: 10px;
      }
    }
  
    .el-dropdown {
      height: 30px;
      border: none!important;
      .el-dropdown-link {
        display: flex;
        align-items: center;
        color: #fff;
        &:hover{
        border: none;
      }
      }
    }
    .fullscreen {
      width: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
}
.header-bottom {
    width: calc(100% - 8px);
    height: 5px;
    background: url(../../assets/images/header.png) no-repeat;
    background-size: calc(100% - 3px) 100%;
    padding: 0 3px;
    margin-left: 3px;
}
}

// 菜单样式
.menu {
        width: 100%;
        list-style: none;
        display: flex;
        line-height: 60px;
        a {
            color: #fff;
            flex:1;
            background: url("../../assets/images/bnt.png") no-repeat center;
            display: flex;
            justify-content: center;
            text-decoration: none;
        }
}

.drawer-main {
  height: 400px;
  display: grid;
  grid-template-columns: repeat(4,1fr);
  grid-template-rows: repeat(4,1fr);
  .module_item {
    display: flex;
    flex-direction: column;
    .img {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      img {
        width: 70px;
        height: 70px;
      }
    }
    p {
      height: 30px;
      width: 100%;
      text-align: center;
    }
  }
}
.module_list {
  height: 300px;
  display: grid;
  grid-template-columns: repeat(6,1fr);
  grid-template-rows: repeat(4,1fr);
  .module_item {
    display: flex;
    flex-direction: column;
    .img {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      img {
        width: 40px;
        height: 40px;
      }
    }
    p {
      height: 30px;
      width: 100%;
      text-align: center;
    }
  }
}
.catchNormal {
  padding-left: 15px;
  padding-right: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  img {
    width: calc(7vh/2);
    height: calc(7vh/2);
    &:hover {
      cursor: pointer;
    }
  }
}

</style>